﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using OCDStudio.SqlAzureBackup.Client.Code;
using OCDStudio.SqlAzureBackup.Client.Properties;
using System.Diagnostics;
using System.IO;

namespace OCDStudio.SqlAzureBackup.Client
{
    public partial class MainForm : Form
    {
        //private List<BackupProfile> profiles = new List<BackupProfile>();
        private Action<string> logToTextBox;

        public MainForm()
        {
            InitializeComponent();
            BackupUtils.Logger= logToTextBox = (p) => { Log(p); };

            UpdateModel();
        }

        private void cmdAddNew_Click(object sender, EventArgs e)
        {
            var p=new NewConnection();
            p.ShowDialog();
            if (p.Profile != null)
            {
                ProfileManager.AddProfile(p.Profile);
                UpdateModel();
            }
        }

        private void UpdateModel()
        {            
            Profiles.Nodes[0].Nodes.Clear();
            foreach (var item in ProfileManager.Profiles)
            {
                Profiles.Nodes[0].Nodes.Add(item.ProfileName, item.Catalog);
            }
        }

        private void cmdRemove_Click(object sender, EventArgs e)
        {
            if (Profiles.SelectedNode != null && MessageBox.Show("Are you sure you want to delete the profile?","Attention",MessageBoxButtons.YesNo,MessageBoxIcon.Question)==DialogResult.Yes)
            {
                ProfileManager.RemoveProfile(ProfileManager.Profiles.Where(p => p.ProfileName == Profiles.SelectedNode.Name).FirstOrDefault());
                UpdateModel();
            }
        }

        private void cmdConnect_Click(object sender, EventArgs e)
        {
            if (Profiles.SelectedNode == null) return;
            var item = ProfileManager.Profiles.Where(p => p.ProfileName == Profiles.SelectedNode.Name).First();
            if (!BackupUtils.CheckConnection(item)) return;
            tables.Items.Clear();

            Profiles.Enabled = tables.Enabled = flow1.Enabled = flow2.Enabled = flow3.Enabled = false;
            var tbs = BackupUtils.GetTables(item);
            tables.Items.AddRange(tbs);
            
            Profiles.Enabled = tables.Enabled = flow1.Enabled = flow2.Enabled = flow3.Enabled = true;
            if (tbs.Any(p => p.Contains('.'))) MessageBox.Show("Some tables contains invalid unsupported characters (i.e dot or commas), we strongly recommend to avoid them!",
                "Attention", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
        }

        private void cmdSelectAll_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < tables.Items.Count; i++)
            {
                tables.SetItemChecked(i, true);
            }
        }

        private void cmdSelectNone_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < tables.Items.Count; i++)
            {
                tables.SetItemChecked(i, false);
            }
        }

        delegate void LogAction(string message);
        public void Log(string message)
        {
            if (txtLog.InvokeRequired)
            {
                txtLog.Invoke(new LogAction(Log), message);
            }
            else
            {
                txtLog.AppendText("\r\n" + message);
            }
        }

        private void cmdBackup_Click(object sender, EventArgs e)
        {
            if (Profiles.SelectedNode == null) return;
            var item = ProfileManager.Profiles.Where(p => p.ProfileName == Profiles.SelectedNode.Name).First();
            if (!BackupUtils.CheckConnection(item)) return;
            if (tables.CheckedItems.Count == 0) return;
            var tbs = tables.CheckedItems.Cast<string>();

            saver.ShowDialog();
            if (!string.IsNullOrEmpty(saver.SelectedPath))
            {
                if (MessageBox.Show("The process could be long-running, proceed?", "Attention", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                {                    
                    cmdBackup.Enabled = cmdStartRestore.Enabled = false;
                    if (BackupUtils.BackupDatabase(saver.SelectedPath,item,tbs))
                    {
                        MessageBox.Show("Completed!");
                    }
                    else MessageBox.Show("Errors during the process, please check the log!");
                    cmdBackup.Enabled = cmdStartRestore.Enabled = true;
                }
            }
        }

        private void cmdRestore_Click(object sender, EventArgs e)
        {            
            if (Profiles.SelectedNode == null) return;
            var item = ProfileManager.Profiles.Where(p => p.ProfileName == Profiles.SelectedNode.Name).First();
            if (!BackupUtils.CheckConnection(item)) return;
            if (tables.CheckedItems.Count == 0) return;
            var tbs = tables.CheckedItems.Cast<string>();

            saver.ShowDialog();
            if (!string.IsNullOrEmpty(saver.SelectedPath) && Directory.Exists(saver.SelectedPath) /*TODO check if is empty*/)
            {
                if (MessageBox.Show("The process could be long-running and could erase existing, proceed?", "Attention", MessageBoxButtons.YesNo)
                    == System.Windows.Forms.DialogResult.Yes)
                {
                    cmdBackup.Enabled = cmdStartRestore.Enabled = false;
                    switch (BackupUtils.RestoreDatabase(saver.SelectedPath, item, tbs))
                    {
                        case RestoreIssue.None:
                            MessageBox.Show("Completed!");
                            break;
                        case RestoreIssue.GenericIssue:
                            MessageBox.Show("Errors during the process, please check the log!");
                            break;
                        case RestoreIssue.DuplicateKey:
                            if (MessageBox.Show("Restore process needs to erase database data in order to perform the restoration? Proceed at your own risk?",
                                "Attention!",MessageBoxButtons.YesNo,MessageBoxIcon.Question)==System.Windows.Forms.DialogResult.Yes){
                                    MessageBox.Show("Future feature");
                            }
                            break;
                    }
                    cmdBackup.Enabled = cmdStartRestore.Enabled = true;
                }
            }
            else
            {
                MessageBox.Show("Destination folder is wrong or empty!","Attention",MessageBoxButtons.OK,MessageBoxIcon.Asterisk);
            }
        }

        private void cmdConnectionSettings_Click(object sender, EventArgs e)
        {
            ShowSettings(SettingPages.CONNECTION);
        }

        private void cmdBackupProfiles_Click(object sender, EventArgs e)
        {
            ShowSettings(SettingPages.PROFILES);
        }

        private void ShowSettings(SettingPages page)
        {
            var frm = new SettingsForm(page);
            frm.OnProfilesSaved += new SettingsForm.SimpleNotifier(frm_OnProfilesSaved);
            frm.ShowDialog();
        }

        void frm_OnProfilesSaved()
        {
            UpdateModel();
        }

        private void cmdBackupSettings_Click(object sender, EventArgs e)
        {
            ShowSettings(SettingPages.BACKUP);
        }
    }
}
